// src/api/index.js (修改后)
import axios from 'axios';
import { useUserStore } from '../stores/user';

// 配置后端API基础地址
const API_BASE_URL = 'http://localhost:8088/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器：添加JWT Token到请求头
apiClient.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理通用错误
apiClient.interceptors.response.use(
  response => response,
  error => {
    const { response } = error;
    if (response) {
      // 处理401未授权（token失效或无权限）
      if (response.status === 401) {
        const userStore = useUserStore();
        userStore.logout();
        window.location.href = '/auth';
      }
      // 显示后端错误信息
      const errorMsg = response.data?.message || '请求失败，请稍后再试';
      return Promise.reject(new Error(errorMsg));
    }
    return Promise.reject(new Error('网络错误，请检查连接'));
  }
);

// 认证相关API
export const login = (username, password, role) => {
  return apiClient.post('/auth/login', { username, password, role });
};

// 公告相关API
export const fetchAnnouncements = () => {
  return apiClient.get('/announcements');
};
export const addAnnouncement = (announcement) => {
  return apiClient.post('/announcements', announcement);
};
export const deleteAnnouncement = (id) => {
  return apiClient.delete(`/announcements/${id}`);
};

// 工单相关API
export const submitServiceTicket = (ticket) => {
  return apiClient.post('/tickets', ticket);
};
export const fetchAllServiceTickets = () => {
  return apiClient.get('/tickets/admin');
};
export const fetchUserServiceTickets = (username) => {
  return apiClient.get(`/tickets/user/${username}`);
};
export const updateServiceTicketStatus = (ticketId, newStatus, newProgressStep) => {
  return apiClient.put(`/tickets/${ticketId}/status`, { newStatus, newProgressStep });
};

// 用户相关API
export const updatePassword = (username, oldPassword, newPassword) => {
  return apiClient.put(`/users/${username}/password`, { oldPassword, newPassword });
};